import threading
from time import sleep


class DevViewsProject(threading.Thread):
    # 类属性
    __id = 0  # 用于id自增，外部无法直接访问
    __threadLock = threading.Lock()  # 线程锁，外部无法直接访问
    threads = list()  # 已创建的线程


    def __init__(self, id=None, name=None, *args, **kwargs):
        threading.Thread.__init__(self)
        DevViewsProject.__id += 1
        self.id = id if id else DevViewsProject.__id
        self.name = name if name else self.id
        DevViewsProject.threads.append(self)  # 收集创建的线程

    def run(self):
        DevViewsProject.__threadLock.acquire()  # 获取锁
        try:
            print("尝试启动前端：http://127.0.0.1:8001\n")
            import subprocess
            # 执行 Bash 命令
            result = subprocess.run('cd Views/AiP && npm run dev'.split(), stdout=subprocess.PIPE, text=True, shell=True)
            # 输出结果
            print(result.stdout)
            
            del DevViewsProject.threads[DevViewsProject.threads.index(self)]  # 删除完成的线程
            print('删除完成的线程：{}'.format(self.id))
        finally:
            pass
        DevViewsProject.__threadLock.release()  # 释放锁


class GoServerProject(threading.Thread):
    # 类属性
    __id = 0  # 用于id自增，外部无法直接访问
    __threadLock = threading.Lock()  # 线程锁，外部无法直接访问
    threads = list()  # 已创建的线程


    def __init__(self, id=None, name=None, *args, **kwargs):
        threading.Thread.__init__(self)
        GoServerProject.__id += 1
        self.id = id if id else GoServerProject.__id
        self.name = name if name else self.id
        GoServerProject.threads.append(self)  # 收集创建的线程

    def run(self):
        GoServerProject.__threadLock.acquire()  # 获取锁
        try:
            print("尝试启动Go Web server：http://127.0.0.1:8002\n")
            import subprocess
            result = subprocess.run('cd OtherServer/GoDemo && go run fileServer.go'.split(), stdout=subprocess.PIPE, text=True, shell=True) # 执行 Bash 命令
            print(result.stdout) # 输出结果
            
            del GoServerProject.threads[GoServerProject.threads.index(self)]  # 删除完成的线程
            print('删除完成的线程：{}'.format(self.id))
        finally:
            pass
        GoServerProject.__threadLock.release()  # 释放锁
